package handler

import (
	"day1106/cache"
	"day1106/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	var data []model.Food
	model.DB.Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": data,
	})
	return
}
func Search(c *gin.Context) {
	name := c.Query("name")
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "2"))
	offset := (page - 1) * size
	var data []model.Food
	redis_key := "food_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("name like ?", "%"+name+"%").Limit(size).Offset(offset).Find(&data)
		jsonData, _ := json.Marshal(data)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour)
	} else {
		json.Unmarshal([]byte(cacheData), &data)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "列表展示成功",
		"data": data,
	})
	return
}
